package com.situation.util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.CreateBucketRequest;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

/**
 * @author TaoMinghui
 * @create 2021-12-08 16:41
 */
public class OSSUtilTemp {
    private static final String endpoint;
    private static final String accessKeyId;
    private static final String accessKeySecret;
    private static final String bucketName;  // 仓库名称

    static {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        endpoint = "oss-cn-hongkong.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        accessKeyId = "LTAI5t5vKcpnACh2KCUhYpYf";
        accessKeySecret = "zcS4Wwzq8kyWBhrcahMPivrZq43dq2";
        bucketName = "eda02";
    }

    /**
     * 获取OSS客户端工具
     * @return
     * @throws FileNotFoundException
     */
    public static OSS getOssClient() throws FileNotFoundException {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        if (ossClient.doesBucketExist(bucketName)) {
            System.out.println("bucket 存在");
        } else {
            // 通过api接口创建bucket仓库
            System.out.println("bucket不存在，创建新的bucket：" + bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(null);
            createBucketRequest.setBucketName(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
            ossClient.shutdown();
        }
        return ossClient;
    }

    /**
     * 将文件fj上传到OSS服务器的fileDir目录下
     * eg:fj,"image"
     * @param fj
     * @param fileDir
     * @throws IOException
     */
    public static String putObjectToOSS(MultipartFile fj,String fileDir) throws IOException {

        //获取原文件名
        String originalFilename = fj.getOriginalFilename();
        //获取文件后缀名
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //使用uuid作为文件名防止重复
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String fileName = uuid+"."+substring;
        final File tempFile = File.createTempFile(uuid, substring);
        //MultipartFile  转换为 File
        fj.transferTo(tempFile);
        // 创建OSSClient实例。
        OSS ossClient = OSSUtilTemp.getOssClient();
        try {
            //容器不存在，就创建
            if(! ossClient.doesBucketExist(bucketName)){
                ossClient.createBucket(bucketName);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
                createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl= fileDir+"/"+fileName;
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketName, fileUrl, tempFile));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            if(null != result){
                System.out.println("==========>OSS文件上传成功,OSS地址："+fileUrl);
            }
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭
            ossClient.shutdown();
        }
        //删除临时生成的文件
        deleteFile(tempFile);
        return fileName;
    }

    private static void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
}
